package com.easy.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easy.back.pojo.PUser;
import com.easy.back.pojo.R;
import com.easy.back.service.IPUserService;
import com.easy.back.utils.BaseContext;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/p")
public class PUserController {
    @Autowired
    private IPUserService userService;

    @GetMapping("/page")
    public R<Page<PUser>> getPage(int page, int pageSize, String name) {
        //构造分页构造器
        Page<PUser> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<PUser> lqw = new LambdaQueryWrapper<>();
        if (name != null) {
            boolean phone = name.matches("0?(13|14|15|17|18)[0-9]{9}");
            boolean email = name.matches("\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}");
            //添加过滤条件
            if (phone) {
                lqw.like(Strings.isNotEmpty(name), PUser::getPhone, name);
            } else if (email) {
                lqw.like(Strings.isNotEmpty(name), PUser::getEmail, name);
            } else {
                lqw.like(Strings.isNotEmpty(name), PUser::getUserName, name);
            }
        }

        //添加排序条件
        lqw.orderByDesc(PUser::getStatus);
        //执行查询
        userService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    @PutMapping("u")
    public R<String> update( @RequestBody PUser pUser) {
        BaseContext.set(pUser);
        LambdaUpdateWrapper<PUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(PUser::getId, pUser.getId());
        wrapper.set(PUser::getStatus, pUser.getStatus());
        try {
            boolean update = userService.update(wrapper);
            if (!update) {
                return R.error("员工信息不存在");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage() + "==========");
        }
        return R.success("用户信息修改成功");
    }
    @DeleteMapping("/d")
    public R<String> delete(String id) {
        BaseContext.set(id);
        userService.removeById(id);
        return R.success("删除用户成功");
    }
}
